package com.spe.common.mybatis.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author limingliang
 * @date 2020/12/11 11:49
 */
public abstract class AbstractGenerator {

    /**
     * 代码生成器
     */
    protected AutoGenerator mpg = new AutoGenerator();

    /**
     * 代码生成参数配置
     */
    private CodeProperties properties;

    public AbstractGenerator(CodeProperties properties) {
        this.properties = properties;
        globalConfig();
        dataSourceConfig();
        packageConfig();
        templateConfig();
        strategyConfig();
        injectionConfig();
        TemplateEngineConfig();
    }

    /**
     * 执行代码生成
     */
    public final void execute() {
        isExists();
        mpg.execute();
    }

    /**
     * 判断项目路径是否存在
     */
    private void isExists() {
        File file = new File(properties.getProjectModulePath());
        if (!file.exists()) {
            throw new MybatisPlusException("项目模块路径" + properties.getProjectModulePath() + "不存在！");
        }
    }

    /**
     * 全局配置
     */
    public void globalConfig() {
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(properties.getProjectModulePath() + "/src/main/java");
        gc.setFileOverride(true);
        gc.setAuthor(properties.getAuthor());
        gc.setOpen(false);
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        mpg.setGlobalConfig(gc);
    }

    /**
     * 数据源配置
     */
    public void dataSourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(properties.getUrl());
        dsc.setDriverName(properties.getDriverClassName());
        dsc.setUsername(properties.getUsername());
        dsc.setPassword(properties.getPassword());
        mpg.setDataSource(dsc);
    }

    /**
     * 包配置
     */
    public void packageConfig() {
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent(properties.getParent());
        mpg.setPackageInfo(pc);
    }

    /**
     * 模板设置
     */
    public void templateConfig() {
        // 配置自定义输出模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
    }

    public void injectionConfig() {
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return properties.getProjectModulePath() + "/src/main/resources/mapper/" + mpg.getPackageInfo().getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
    }

    /**
     * 策略配置
     */
    public void strategyConfig() {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setTablePrefix("sys_");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(mpg.getPackageInfo().getModuleName() + "_");
        mpg.setStrategy(strategy);
    }

    /**
     * 模板配置
     */
    public void TemplateEngineConfig() {
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    }

    public static void listFiles(File originFile) {
        File[] files = originFile.listFiles();
        for (File file : files) {
            if (file.isDirectory() && file.getName().startsWith("spe-")) {
                System.out.println(originFile.getName() + " -> " + file.getName());
                listFiles(file);
            }
        }
    }

    public String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

}
